<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Str;
use Qbhy\HyperfAuth\Authenticatable;
use Qbhy\HyperfAuth\AuthMiddleware as BaseAuthMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\HyperfAuth\Exception\UnauthorizedException;

class AuthMiddleware extends BaseAuthMiddleware
{
    protected $guards = ['backend-api-jwt'];

    /**
     * @Inject
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var \Hyperf\HttpServer\Contract\ResponseInterface
     */
    protected $response;

    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->isExcepted()) {
            return $handler->handle($request);
        }

        try {
            foreach ($this->guards as $name) {
                $guard = $this->auth->guard($name);
                $user = $guard->user();

                if (! $user instanceof Authenticatable) {
                    throw new UnauthorizedException("Without authorization from {$guard->getName()} guard", $guard);
                }
                if (!$user->user_status) {
                    throw new UnauthorizedException("此账号已被禁用，请联系系统管理员", $guard);
                }
            }
        } catch (\Throwable $e) {
           return $this->response->json([
               'code' => $e->getCode(),
               'message' => $e->getMessage(),
               'data' => [],
           ]);
        }

        return $handler->handle($request);
    }

    /**
     * 判断当前uri是否不需认证
     * @return bool
     */
    protected function isExcepted()
    {
        $uri_path = $this->request->getUri()->getPath();
        foreach ($this->config->get('admin.auth.except') as $except) {
            $methods = [];
            if (Str::contains($except, ':')) {
                list($methods, $except) = explode(':', $except);
                $methods = explode(',', $methods);
            }
            $methods = array_map('strtoupper', $methods);

            if (($uri_path === $except || @preg_match("/{$except}/", $uri_path)) &&
                (empty($methods) || in_array($this->request->getMethod(), $methods))) {
                return true;
            }
        }

        return false;
    }
}
